package Entity;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自动批改类：对比习题与练习文件，生成批改结果并存储
 */
public class Corrector {
    private static final double SINGLE_SCORE = 1.0; // 单题分值（1分制）

    /**
     * 自动批改练习
     * @param exerciseFilePath 习题文件路径（含正确答案）
     * @param practiceFilePath 练习文件路径（含小明答案）
     * @return 批改文件路径
     */
    public String correctPractice(String exerciseFilePath, String practiceFilePath) throws IOException {
        // 1. 读取习题与练习记录
        List<Exercise> exercises = CsvFileUtil.readExercises(exerciseFilePath);
        List<PracticeRecord> practiceRecords = CsvFileUtil.readPracticeRecords(practiceFilePath);

        // 2. 校验习题与练习记录数量一致（防御性编程）
        if (exercises.size() != practiceRecords.size()) {
            throw new RuntimeException("习题数量与练习记录不匹配：习题" + exercises.size() + "道，练习" + practiceRecords.size() + "道");
        }

        // 3. 构建习题ID到习题的映射（提高匹配效率）
        Map<String, Exercise> exerciseMap = new HashMap<>();
        for (Exercise exercise : exercises) {
            exerciseMap.put(exercise.getExerciseId(), exercise);
        }

        // 4. 逐题批改，计算得分
        List<String[]> correctionData = new ArrayList<>();
        double totalScore = 0.0;
        int correctCount = 0;

        // 添加批改文件表头
        correctionData.add(new String[]{
                "ExerciseId", "Num1", "Operator", "Num2",
                "CorrectAnswer", "UserAnswer", "IsCorrect", "Score"
        });

        for (PracticeRecord record : practiceRecords) {
            String exerciseId = record.getExerciseId();
            Exercise exercise = exerciseMap.get(exerciseId);
            if (exercise == null) {
                throw new RuntimeException("练习记录中的习题ID不存在：" + exerciseId);
            }

            // 判断答案是否正确（未答题视为错误）
            boolean isCorrect = record.getUserAnswer() != -1 && record.getUserAnswer() == exercise.getCorrectAnswer();
            double score = isCorrect ? SINGLE_SCORE : 0.0;
            if (isCorrect) correctCount++;
            totalScore += score;

            // 构建批改记录
            correctionData.add(new String[]{
                    exerciseId,
                    String.valueOf(exercise.getNum1()),
                    String.valueOf(exercise.getOperator()),
                    String.valueOf(exercise.getNum2()),
                    String.valueOf(exercise.getCorrectAnswer()),
                    String.valueOf(record.getUserAnswer()),
                    String.valueOf(isCorrect),
                    String.valueOf(score)
            });
        }

        // 5. 添加总分与正确率（作为最后一行）
        double accuracy = (double) correctCount / exercises.size() * 100;
        correctionData.add(new String[]{
                "总分", "", "", "", "", "", "", String.valueOf(totalScore),
                "正确率", String.format("%.2f%%", accuracy)
        });

        // 6. 生成批改文件路径（关联练习文件）
        String correctionFilePath = practiceFilePath.replace(".csv", "_Corrected.csv");
        // 写入批改文件
        writeCorrectionToCsv(correctionData, correctionFilePath);

        System.out.println("批改完成！总分：" + totalScore + "，正确率：" + String.format("%.2f%%", accuracy));
        System.out.println("批改文件路径：" + correctionFilePath);
        return correctionFilePath;
    }

    /**
     * 将批改结果写入CSV文件
     */
    private void writeCorrectionToCsv(List<String[]> correctionData, String filePath) throws IOException {
        com.csvreader.CsvWriter csvWriter = new com.csvreader.CsvWriter(filePath, ',', StandardCharsets.UTF_8);
        for (String[] row : correctionData) {
            csvWriter.writeRecord(row);
        }
        csvWriter.close();
    }
}